/*
 * @Author: YZ
 * @Date: 2024/1/32
 * @Description: 便捷注入路由
 */
import { Application } from 'egg';
import BaseMethods from '@app/common/BaseMethods';

enum RequestMethods {
  GET = 'get',
  POST = 'post',
  PUT = 'put',
  DELETE = 'delete',
  ALL = 'all',
  PATCH = 'patch'
}
interface RouteStore {
  [key: string]: Array<{ path: string, method: RequestMethods }>
}
const routeStore: RouteStore = {}

/**
 * 路由装饰器
 * @param path 路径
 * @param method 请求方法（get，post等）
 */
function request(target: any, method: RequestMethods, path: string) {
  const k = target.constructor.name
  const el = {
    path: path,
    method,
  }
  if (routeStore[k]) {
    routeStore[k].push(el)
  } else {
    routeStore[k] = [el]

  }
}

function GET(target: any, path: any): void {
  request(target, RequestMethods.GET, path);
}

function POST(target: any, path: any): void {
  request(target, RequestMethods.POST, path);
}

function PUT(target: any, path: any): void {
  request(target, RequestMethods.PUT, path);
}

function DEL(target: any, path: any): void {
  request(target, RequestMethods.DELETE, path);
}

function ALL(target: any, path: any): void {
  request(target, RequestMethods.ALL, path);
}


function PATCH(target: any, path: any): void {
  request(target, RequestMethods.PATCH, path);
}

/**
 * 在router.ts中直接使用AddRouter(app);即可完成自动注入路由
 * @param app application
 * @param prefix 就是所有路由的前缀
 */
export function AddRouter(app: Application, prefix: string = 'api') {
  const { router, controller } = app;
  const keys = Object.keys(routeStore)
  keys.forEach(k => {
    const key = BaseMethods.humpToUnderline(k)
    const list = routeStore[k];
    list.forEach(el => {
      router[el.method](`/${prefix}/${key}/${ BaseMethods.humpToUnderline(el.path)}`,controller[key][el.path])
    })
  })
}

export {
  POST,
  GET,
  PUT,
  DEL,
  PATCH,
  ALL,
};
